GBML manual / Maths

inverse_lerp

Says how far value is from a to b as a number from 0 to 1: 0 when value is a, 1 when it is b, 0.5 halfway. It is lerp turned round. Use it to turn a health of 0 to 50 into a bar that is 0 to 1 full: fill = inverse_lerp(0, 50, hp).

Sega Genesis: not built yet

On other consoles this differs: see Side by side and How the consoles differ.

Syntax

inverse_lerp(a, b, value) -> real

Arguments

NameType
areal
breal
valuereal

Returns

real

Description

Says how far value is from a to b, as a number from 0 to 1. It is lerp turned round: lerp takes a 0-to-1 number and gives a place between a and b; inverse_lerp takes a place and gives the 0-to-1 number.

It is how you turn a health of 0 to 50 into a bar that is 0 to 1 full, or a distance into a volume.

Example

var hp = 20;
var fill = inverse_lerp(0, 50, hp);
var bar_width = fill * 32;

fill is 0.4 (20 is 40 percent of the way from 0 to 50) and bar_width is 12.8 pixels of a 32-pixel bar.

The small print

Cost

One divide, done exactly.

On the GBA

It does NOT stop at 0 and 1: a value past b gives more than 1 and a value before a gives less than 0, so wrap it in clamp(.., 0, 1) when a bar must not overflow. If a and b are the same number there is no distance to measure along, so the answer is 0 and the game carries on. The divide is done exactly (the sum is taken in 64 bits), so the answer is right to one 1/4096. An answer too big for a real stops at the biggest or smallest real instead of wrapping round.

See also: lerpclampeasetween